/*
** Zabbix
** Copyright (C) 2001-2023 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/

package yashandb

import (
	"context"
	"strings"
	"git.zabbix.com/ap/plugin-support/zbxerr"
)

func fraHandler(ctx context.Context, conn YasClient, params map[string]string, _ ...string) (interface{}, error) {
	var FRA string

	row, err := conn.QueryRow(ctx, `

WITH value_stats AS (
    SELECT SUM(BLOCK_SIZE * BLOCKS) AS total_blocks
    FROM V$ARCHIVED_LOG
), arch_clean_upper_threshold AS (
    SELECT CASE 
        WHEN VALUE LIKE '%T' THEN TRIM(TRAILING 'T' FROM VALUE) * 1024 * 1024 * 1024 * 1024
        WHEN VALUE LIKE '%G' THEN TRIM(TRAILING 'G' FROM VALUE) * 1024 * 1024 * 1024
        WHEN VALUE LIKE '%M' THEN TRIM(TRAILING 'M' FROM VALUE) * 1024 * 1024
        WHEN VALUE LIKE '%K' THEN TRIM(TRAILING 'K' FROM VALUE) * 1024
        WHEN REGEXP_LIKE(VALUE, '^[1-9]+[0-9]*$') = TRUE THEN TO_NUMBER(VALUE)
    END AS value
    FROM V$PARAMETER
    WHERE name = 'ARCH_CLEAN_UPPER_THRESHOLD'
)
SELECT 
'{' || LISTAGG('"' || METRIC || '":' || value,',') || '}'
FROM (
    SELECT 'usable_pct' AS METRIC, NVL(ROUND(100 * (b.total_blocks / a.value),2),0) AS value
    FROM arch_clean_upper_threshold a, value_stats b
    UNION 
    SELECT 'space_limit' AS METRIC, value
    FROM arch_clean_upper_threshold
    UNION 
    SELECT 'number_of_files' AS METRIC, COUNT(1) AS value
    FROM V$ARCHIVED_LOG
    UNION 
    SELECT 'space_used' AS METRIC, NVL(SUM(BLOCK_SIZE * BLOCKS),0) AS value
    FROM V$ARCHIVED_LOG
    UNION 
    SELECT 'space_reclaimable' AS METRIC, NVL(SUM(b.size),0) AS value
    FROM (SELECT REGEXP_SUBSTR(RCY_POINT, '[^-]+', 1, 2, 'i') AS value FROM v$database) a, (SELECT SEQUENCE# AS value, BLOCK_SIZE * BLOCKS AS size FROM V$ARCHIVED_LOG) b
    WHERE a.value > b.value
    UNION 
    SELECT 'restore_point' AS METRIC, 0 AS value
    FROM DUAL
)
	`)
	if err != nil {
		return nil, zbxerr.ErrorCannotFetchData.Wrap(err)
	}

	err = row.Scan(&FRA)
	if err != nil {
		return nil, zbxerr.ErrorCannotFetchData.Wrap(err)
	}
	FRA = strings.ReplaceAll(FRA, "\":.", "\":0.")
	return FRA, nil
}
